package day21;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 
 * ObjectStreamDemo.java
 * 
 * @author wangbiao<br/>
 *         email:785497344@qq.com
 * @description 把一个对象序列化存放在文件中，然后再读取出来。 
 * 静态字段不会被序列化，被transient关键字修饰的字段也不会序列化
 * @since 1.0.0
 * @date 2013-6-28下午11:16:38
 * 
 */
public class ObjectStreamDemo {

	public static void main(String[] args) {
		writeObject();
		readObject();
	}

	// 读取一个序列化的对象
	public static void readObject() {
		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(new FileInputStream("person.object"));
			Person person = (Person) ois.readObject();
			System.out.println(person);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			if (null != ois) {
				try {
					ois.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	// 把一个对象序列化存到一个文件中
	public static void writeObject() {
		ObjectOutputStream oos = null;
		Person person = new Person("lisi", 18);
		try {
			oos = new ObjectOutputStream(new FileOutputStream("person.object"));
			oos.writeObject(person);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != oos) {
				try {
					oos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
